package com.yincai.carefreewater.ui;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.method.ReplacementTransformationMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.yincai.carefreewater.R;
import com.yincai.carefreewater.base.BaseActivity;
import com.yincai.carefreewater.callback.StringCallback;
import com.yincai.carefreewater.constant.URLConstant;
import com.yincai.carefreewater.db.SaveDao;
import com.yincai.carefreewater.db.SaveInfo;
import com.yincai.carefreewater.tool.JumpTool;
import com.yincai.carefreewater.tool.ShareTool;
import com.yincai.carefreewater.tool.ToastTool;
import com.yincai.carefreewater.tool.WindowTool;
import com.yincai.carefreewater.usb.UsbTool;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.sql.SQLException;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 设置
 *
 */
public class SetActivity extends BaseActivity {

    @BindView(R.id.set_close)
    ImageView setClose;
    @BindView(R.id.set_pai)
    Button setPai;
    @BindView(R.id.set_xiao)
    Button setXiao;
    @BindView(R.id.set_huan)
    Button setHuan;
    @BindView(R.id.set_guanli)
    Button setGuanli;
    @BindView(R.id.set_rong)
    Button setRong;
    @BindView(R.id.set_pwd)
    Button setPwd;
    @BindView(R.id.set_input_edit)
    EditText setInputEdit;
    @BindView(R.id.set_bind_btn)
    Button setBindBtn;
    @BindView(R.id.set_rest_btn)
    Button setRestBtn;
    @BindView(R.id.set_init)
    Button setInit;
    @BindView(R.id.set_setting)
    Button setSetting;
    private LayoutInflater inflater;
    private SaveDao saveDao;
    Handler closeHandler=new Handler();
    Runnable closRun=new Runnable() {
        @Override
        public void run() {
            finish();
        }
    };

    private Handler usbHandler =new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            String str=msg.obj.toString();
            switch (msg.what) {
                case -1:
                    ToastTool.toast(str);
                    break;
                case 0:
                    ToastTool.toast(str);
                    break;
                case 1:
                    try {
                        if(str.contains("AT+OK")){
                            if(msg_send.contains("=")){
                                msg_send=msg_send.substring(0,msg_send.indexOf("="));
                            }
                            switch (msg_send){
                                case  "AT+CS4":
                                    ToastTool.toast("凉水水水量设置成功");
                                    break;
                                case  "AT+CS2":
                                    ToastTool.toast("热水水量设置成功");
                                    break;
                                case  "AT+CZ":
                                    ToastTool.toast("复位");
                                    break;
                                case  "AT+BEGIN":
                                    ToastTool.toast("设备启用");
                                    break;
                                case  "AT+END":
                                    ToastTool.toast("设备停用");
                                    break;
                                case  "AT+STOP":
                                    ToastTool.toast("停止");
                                    break;
                                case  "AT+KEYON":
                                    ToastTool.toast("触摸键启用");
                                    break;
                                case  "AT+KEYOFF":
                                    ToastTool.toast("触摸键停用");
                                    break;
                                case  "AT+PSSTOP":
                                    ToastTool.toast("排水停止");
                                    break;
                                case  "AT+XD":
                                    ToastTool.toast("消毒开始");
                                    break;
                                case  "AT+CS3":
                                    ToastTool.toast("桶装水容量设置成功");
                                    break;
                                case "AT+CSH":
                                    ToastTool.toast("初始化成功");
                                    msg_send="AT+PS";
                                    writeToUSb(msg_send);
                                    break;
                                case "AT+PS":
                                //    ToastTool.toast("排水成功");
                                    msg_send="AT+LBKPS";
                                    writeToUSb(msg_send);
                                    break;
                                case "AT+LBKPS":
                                 //   ToastTool.toast("凉白开排水成功");
                                    break;
                                case "AT+HT":
                                    ToastTool.toast("换桶成功");
                                    break;
                            }
                        }
                        Log.i(TAG, "设置Message: " + str);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
            }
            return false;
        }
    });
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        WindowTool.hideBottomUIMenu(this);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_set);
        ButterKnife.bind(this);
        inflater=LayoutInflater.from(this);
        saveDao=new SaveDao(SetActivity.this);
        closeHandler.postDelayed(closRun,5*60*1000); //5 分钟后自动关闭
        try {
            SaveInfo qur_b = saveDao.queryById("id", "1");

            if(qur_b!=null&&qur_b.getDevice().length()>1){
                setInputEdit.setText(qur_b.getDevice());
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

    }
    @Override
    protected void onResume() {
        super.onResume();
        Log.i(TAG, "setactivityononResume:");
        UsbTool.getInstance().setHandler(usbHandler);
        UsbTool.getInstance().openUsbDevice(SetActivity.this);
     //   WindowTool.hideMenu(this);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        closeHandler.removeCallbacks(closRun);
    }

    @Override
    protected void onStop() {
        super.onStop();
        Log.i(TAG, "setactivityonStop:");
        try {
            UsbTool.getInstance().unRegist();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClick({R.id.set_close, R.id.set_pai, R.id.set_xiao, R.id.set_huan, R.id.set_guanli, R.id.set_rong, R.id.set_pwd, R.id.set_bind_btn, R.id.set_rest_btn, R.id.set_init, R.id.set_setting})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.set_close:
              finish();
          //    JumpTool.jump(SetActivity.this,MainActivity.class);
                closeHandler.removeCallbacks(closRun);
                break;
            case R.id.set_pai: //排水
                paishui();
              WindowTool.hideMenu(SetActivity.this);
                break;
            case R.id.set_xiao:
                xiaodu();
                break;
            case R.id.set_huan: //换桶
 //           JumpTool.jump(this,HuanTongActivity.class);
                msg_send="AT+HT";
                writeToUSb(msg_send);
                sendHuanTong();
                break;
            case R.id.set_guanli://绑管理员
            //    bindGuanli();
                createQr("");
                break;
            case R.id.set_rong:// 水桶容量
             //   setShuiTong();
                AlertDialog.Builder builder2 =new AlertDialog.Builder(SetActivity.this);
                builder2.setTitle("设置水桶容量");
                String shui_which = ShareTool.getInfo(SetActivity.this, "shui_which");
                int which=0;
                if(shui_which!=null&&shui_which.length()>0){
                    which=Integer.parseInt(shui_which);
                }
                builder2.setSingleChoiceItems(shui_array, which, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                        //  ToastTool.toast("水桶容量"+shui_array[which]);
                        String str="AT+CS3="+shui_value[which];
                        count_liang=shui_value[which];
                        msg_send="AT+CS3";
                        ShareTool.saveInfo(SetActivity.this,"shui_which",which+"");
                        ShareTool.saveInfo(SetActivity.this,"shui_liang",count_liang+"");
                        writeToUSb(str);
                    }
                });
                builder2.show();
                break;
            case R.id.set_pwd: //修改管理员密码
                changePwd();
                break;
            case R.id.set_bind_btn: //绑设备号
                String dev_code = setInputEdit.getText().toString();
                if(dev_code.equals("0000000000")||dev_code.length()<16){
                    ToastTool.toast("设备号位数不正确，请检查");
                }else {
                    bindShebei(dev_code);
                }
                break;
            case R.id.set_rest_btn:  //重置 设备号
                dev_code = setInputEdit.getText().toString();
                if(dev_code.equals("0000000000")||dev_code.length()<16){
                    ToastTool.toast("还未绑定设备号");
                }else {
                    restShebei(setInputEdit);
                }
                break;
            case R.id.set_init: //初始化
                initDev();

                break;
            case R.id.set_setting: //发送口令
                bindCmd();
                break;
        }
    }

    /**
     * 换桶
     */
    private void huantong() {
        AlertDialog.Builder    bu =new AlertDialog.Builder(SetActivity.this);
        bu.setTitle("确认换桶提示!");
        bu.setMessage("确定换桶吗?");
        bu.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                msg_send="AT+HT";
                writeToUSb(msg_send);
                //通知服务器
                sendHuanTong();
            }
        });
        bu.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        bu.setCancelable(false);
        bu.show();
    }
    /**
     *
     * 发送换桶给服务端
     */
    private  void sendHuanTong(){
        String bar_code= ShareTool.getInfo(SetActivity.this,"bar_code");
        try {
            if (bar_code.length() < 1) {
                SaveInfo bar = saveDao.queryById("id", "1");
                bar_code = bar.getBarcode();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        String path = URLConstant.HOST + URLConstant.DEVICE_REPLACE + "bar_code=" + bar_code ;
        okTool.doGet(path, new StringCallback() {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onFailure(Call call, IOException e) {
            }

            @Override
            public void onSuccess(Response response, String t) {
                //  Log.i(TAG, "onSuccess: "+t);
                try {
                    JSONObject json=new JSONObject(t);
                    String code = json.optString("code");
                    String msg = json.optString("msg");
                    if(code.equals("100")){
                    }else {
                        ToastTool.toast(msg);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onError(Response response, String errorMsg) {

            }
        });
    }

    /**
     * 给机器发送口令
     */
    private void setCmd() {
        AlertDialog.Builder builder =new AlertDialog.Builder(SetActivity.this);
        builder.setCancelable(false);
        final View dia=inflater.inflate(R.layout.layout_set_command,null);
        builder.setView(dia);
        final AlertDialog dialog= builder.create();
        final EditText admin_cmd = (EditText) dia.findViewById(R.id.set_admin_cmd);
        admin_cmd.setTransformationMethod(new ReplacementTransformationMethod() {
            @Override
            protected char[] getOriginal() {
                char[] originalCharArr = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' };
                return originalCharArr;
            }

            @Override
            protected char[] getReplacement() {
                char[] replacementCharArr = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z' };
                return replacementCharArr;
            }
        });

    final Button  cancle = dia.findViewById(R.id.set_admin_cancle);
        final Button  post = dia.findViewById(R.id.set_admin_post);
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                dialog.dismiss();
            }
        });
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String cmd = admin_cmd.getText().toString().toUpperCase();
                msg_send="AT+"+cmd;
                writeToUSb(msg_send);
            }
        });

        dialog.show();


    }

    /**
     * 初始化
     */
    private void initDev() {
        AlertDialog.Builder builder=new AlertDialog.Builder(SetActivity.this);
        builder.setCancelable(false);
        View dia=inflater.inflate(R.layout.layout_shebei_diolag,null);
        builder.setView(dia);
         final AlertDialog   dialog= builder.create();
        final EditText admin_pwd = (EditText) dia.findViewById(R.id.sheibei_dialog_txt);
        Button post= (Button) dia.findViewById(R.id.sheibei_dialog_post);
        Button cancle= (Button) dia.findViewById(R.id.sheibei_dialog_cancle);

        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String  content=admin_pwd.getText().toString();
                if(content.equals("123123")){
                    msg_send="AT+CSH";
                    writeToUSb(msg_send);
                    dialog.dismiss();
                    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);  //隐藏键盘
                }else {
                    ToastTool.toast("输入密码错误");
                }
            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    /**
     *设置水桶容量
     */
    private  String [] shui_array=new String[]{"7.5L","9L","16.8L","18.9L"};
    private  int [] shui_value=new int[]{7500,9000,16800,18900};
    private String    msg_send="";
    private  int count_liang=18900;
    private void setShuiTong() {
        AlertDialog.Builder builder =new AlertDialog.Builder(SetActivity.this);
        builder.setCancelable(false);
        View dia=inflater.inflate(R.layout.layout_shebei_diolag,null);
        builder.setView(dia);
        builder.setTitle("管理员密码");
       final AlertDialog   shui_dialog=builder.create();
        final EditText admin_pwd = (EditText) dia.findViewById(R.id.sheibei_dialog_txt);
        admin_pwd.setHint("请输入管理员密码");
        Button post= (Button) dia.findViewById(R.id.sheibei_dialog_post);
        Button cancle= (Button) dia.findViewById(R.id.sheibei_dialog_cancle);
        final String bar_pwd=ShareTool.getInfo(SetActivity.this,"bar_pwd");
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String  pwd=admin_pwd.getText().toString();
                if(pwd.length()==0){
                    ToastTool.toast("请输入绑定设备时返回的管理员密码");
                }else if(pwd.equals(bar_pwd)) {

                        shui_dialog.dismiss();

                    AlertDialog.Builder builder2 =new AlertDialog.Builder(SetActivity.this);
                    builder2.setTitle("设置水桶容量");
                    String shui_which = ShareTool.getInfo(SetActivity.this, "shui_which");
                    int which=0;
                    if(shui_which!=null&&shui_which.length()>0){
                        which=Integer.parseInt(shui_which);
                    }
                    builder2.setSingleChoiceItems(shui_array, which, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                            //  ToastTool.toast("水桶容量"+shui_array[which]);
                            String str="AT+CS3="+shui_value[which];
                            count_liang=shui_value[which];
                            msg_send="AT+CS3";
                            ShareTool.saveInfo(SetActivity.this,"shui_which",which+"");
                            ShareTool.saveInfo(SetActivity.this,"shui_liang",count_liang+"");
                            writeToUSb(str);
                        }
                    });
                    builder2.show();
                }

            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shui_dialog.dismiss();
            }
        });

        shui_dialog.show();




    }

    /**
     * 修改管理员密码
     */
    private void changePwd() {
        AlertDialog.Builder builder1 =new AlertDialog.Builder(SetActivity.this);
        View view = inflater.inflate(R.layout.layout_set_change_pwd, null);
        Button post1= (Button) view.findViewById(R.id.set_change_post);
        final Button cancle1= (Button) view.findViewById(R.id.set_change_cancle);
        final EditText mOld_pwd,mPwd,mRePwd;
        mOld_pwd= (EditText) view.findViewById(R.id.set_change_edit_old_pwd);
        mPwd= (EditText) view.findViewById(R.id.set_change_edit_pwd);
        mRePwd= (EditText) view.findViewById(R.id.set_change_edit_re_pwd);
        builder1.setView(view);
      final AlertDialog  change_dialog=builder1.create();
        String  my_pwd=ShareTool.getInfo(SetActivity.this,"bar_pwd");
        final String mycode=ShareTool.getInfo(SetActivity.this,"bar_code");
        post1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String old = mOld_pwd.getText().toString();
                final String pwd = mPwd.getText().toString();
                String re_pwd = mRePwd.getText().toString();
                if(mycode==null||mycode.length()==0){
                    ToastTool.toast("还没有绑定设备");
                }
                else if(pwd.length()==0){

                    ToastTool.toast("请输入新密码");
                }else if(re_pwd.length()==0){

                    ToastTool.toast("请再次输入新密码");
                }else if(!re_pwd.equals(pwd)){

                    ToastTool.toast("两次输入密码不一致");
                }else {

                    String path= URLConstant.HOST + URLConstant.UPDATEPASS+"bar_code="+mycode+"&old_pwd="+old+"&new_pwd="+pwd;
                    okTool.doGet(path, new StringCallback() {
                        @Override
                        public void onBeforeRequest(Request request) {
                        }
                        @Override
                        public void onFailure(Call call, IOException e) {
                        }

                        @Override
                        public void onSuccess(Response response, String t) {
                            JSONObject jsonObject= null;
                            try {
                                jsonObject = new JSONObject(t);
                                String code1 = jsonObject.optString("code");
                                String msg=jsonObject.optString("msg");
                                if(code1.equals("100")) {
                                    ToastTool.toast("修改成功");
                                    //更新pwd 到数据库
                                    ShareTool.saveInfo(SetActivity.this,"bar_pwd",pwd);
                                    SaveInfo id = saveDao.queryById("id", "1");
                                    id.setPwd(pwd);
                                    saveDao.update(id);
                                    change_dialog.dismiss();
                                }else {
                                    ToastTool.toast(msg);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onError(Response response, String errorMsg) {

                        }
                    });
                }
            }
        });
        cancle1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                change_dialog.dismiss();
            }
        });
        change_dialog.show();




    }

    /**
     * 绑定管理
     */
    private void bindGuanli() {
        AlertDialog.Builder builder =new AlertDialog.Builder(SetActivity.this);
        builder.setCancelable(false);
        View dia=inflater.inflate(R.layout.layout_shebei_diolag,null);
        builder.setView(dia);
        builder.setTitle("管理员密码");
     final AlertDialog  guanli_dialog=builder.create();

        final EditText admin_pwd = (EditText) dia.findViewById(R.id.sheibei_dialog_txt);
        admin_pwd.setHint("请输入管理员密码");
        Button post= (Button) dia.findViewById(R.id.sheibei_dialog_post);
        Button cancle= (Button) dia.findViewById(R.id.sheibei_dialog_cancle);
        final String code=ShareTool.getInfo(SetActivity.this,"scode");
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String  pwd=admin_pwd.getText().toString();
                if(code==null||code.length()==0){
                    ToastTool.toast("还未绑定设备");
                }else  if(pwd.length()==0){
                    ToastTool.toast("请输入绑定设备时返回的管理员密码");
                }else {
                    guanli_dialog.dismiss();
                    createQr(pwd);
                }

            }
        });
        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                guanli_dialog.dismiss();
            }
        });

        guanli_dialog.show();

    }
    /**
     * 生成二维码
     */
    private void createQr(String pwd) {

        String bar_code=ShareTool.getInfo(SetActivity.this,"bar_code");
        String bar_pwd=ShareTool.getInfo(SetActivity.this,"bar_pwd");
    //    if(pwd.equals(bar_pwd)) {
           // String path = URLConstant.HOST + URLConstant.TWOCODE + "bar_code=" + bar_code + "&pwd=" + pwd;
            String path = URLConstant.HOST + URLConstant.TWOCODE + "bar_code=" + bar_code;
            okTool.doGet(path, new StringCallback() {
                @Override
                public void onBeforeRequest(Request request) {

                }

                @Override
                public void onFailure(Call call, IOException e) {


                }

                @Override
                public void onSuccess(Response response, String t) {
                    try {
                        JSONObject jsonObject = new JSONObject(t);
                        String code1 = jsonObject.optString("code");
                        String msg = jsonObject.optString("msg");
                        if (code1.equals("100")) {
                            JSONObject result = jsonObject.optJSONObject("result");
                            String two_code = result.optString("two_code");
                            AlertDialog.Builder builder = new AlertDialog.Builder(SetActivity.this);
                            View v = inflater.inflate(R.layout.layout_qr, null);
                            ImageView img = (ImageView) v.findViewById(R.id.qr_img_qr);
                            Button btn = (Button) v.findViewById(R.id.qr_btn_back);
                            Glide.with(SetActivity.this).load(URLConstant.HOST + two_code).into(img);
                            builder.setView(v);
                           final AlertDialog qr_dialog = builder.create();
                            btn.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    qr_dialog.dismiss();
                                }
                            });
                            qr_dialog.show();


                        } else {

                            ToastTool.toast(msg);
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                }

                @Override
                public void onError(Response response, String errorMsg) {

                }
            });

 //       }else {
  ///          ToastTool.toast("管理员密码错误");

   //     }


    }
    /**
     * 排水
     */
    private void paishui() {
        AlertDialog.Builder builder =new AlertDialog.Builder(SetActivity.this);
        builder.setCancelable(false);
        builder.setTitle("排水提示!");
        builder.setMessage("\n已准备好接废水设备，准备排水？\n");

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                JumpTool.jump(SetActivity.this,PaidShuiActivity.class,"activity","set");
                finish();
            }
        });
        builder.show();
    }
    /**
     * 排水
     */
    private void xiaodu() {
        AlertDialog.Builder builder =new AlertDialog.Builder(SetActivity.this);
        builder.setCancelable(false);
        builder.setTitle("消毒提示!");
        builder.setMessage("\n已确定准备好消毒？\n");

        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                dialogInterface.dismiss();

            }
        });
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                JumpTool.jump(SetActivity.this,XiaoduActivity.class);


            }
        });
        builder.show();
    }

    /**
     * @param dev_code
     * 绑定设备号
     */
    private void bindShebei(final String dev_code) {
        AlertDialog.Builder builder =new AlertDialog.Builder(SetActivity.this);
        builder.setCancelable(false);
        final View dia=inflater.inflate(R.layout.layout_shebei_diolag,null);
        builder.setView(dia);
        final AlertDialog dialog= builder.create();
        final EditText admin_pwd = (EditText) dia.findViewById(R.id.sheibei_dialog_txt);
        Button post= (Button) dia.findViewById(R.id.sheibei_dialog_post);
        Button cancle= (Button) dia.findViewById(R.id.sheibei_dialog_cancle);
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String  content=admin_pwd.getText().toString();
                if(content.length()==0){
                    ToastTool.toast("请输入厂家密码");
                }else{
                    //验证密码 重置设备号
                    bindCode(content,dev_code);
                    dialog.dismiss();
                }

            }
        });


        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();

    }
    /**
     *
     * 验证发送口令密码
     */
    private void bindCmd() {
        AlertDialog.Builder builder =new AlertDialog.Builder(SetActivity.this);
        builder.setCancelable(false);
        final View dia=inflater.inflate(R.layout.layout_shebei_diolag,null);
        builder.setView(dia);
        final AlertDialog dialog= builder.create();
        final EditText admin_pwd = (EditText) dia.findViewById(R.id.sheibei_dialog_txt);
        Button post= (Button) dia.findViewById(R.id.sheibei_dialog_post);
        Button cancle= (Button) dia.findViewById(R.id.sheibei_dialog_cancle);
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String  content=admin_pwd.getText().toString();
                if(content.length()==0){
                    ToastTool.toast("请输入厂家密码");
                }else{
                    //验证密码 重置设备号
                    requestcmd(content);
                    dialog.dismiss();
                }

            }
        });


        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();

    }
    /**
     *
     * 解除绑定设备号
     */
    private void restShebei(final EditText txt) {
        AlertDialog.Builder builder =new AlertDialog.Builder(SetActivity.this);
        builder.setCancelable(false);

        final View dia=inflater.inflate(R.layout.layout_shebei_diolag,null);
        builder.setView(dia);
        final AlertDialog dialog= builder.create();
        final EditText admin_pwd = (EditText) dia.findViewById(R.id.sheibei_dialog_txt);
        Button post= (Button) dia.findViewById(R.id.sheibei_dialog_post);
        Button cancle= (Button) dia.findViewById(R.id.sheibei_dialog_cancle);
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String  content=admin_pwd.getText().toString();
                if(content.length()==0){
                    ToastTool.toast("请输入厂家密码");
                }else{
                    //验证密码 重置设备号
                    restCode(content,txt);
                    dialog.dismiss();
                }

            }
        });


        cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });

        dialog.show();

    }
    /**
     * @param content
     *
     * 重置设备号
     */
    private void restCode(String content, final EditText txt) {
        final String device=txt.getText().toString();
        String path= URLConstant.HOST + URLConstant.FIRMPASSWORD+"firmpwd="+content;
        okTool.doGet(path, new StringCallback() {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onSuccess(Response response, String t) {

                try {
                    JSONObject jsonObject=new JSONObject(t);
                    String code1 = jsonObject.optString("code");
                    String msg=jsonObject.optString("msg");
                    if(code1.equals("100")){   //验证密码成功开始解绑
                        String path= URLConstant.HOST + URLConstant.DEVICERESET+"bar_code="+device;
                        okTool.doGet(path, new StringCallback() {
                            @Override
                            public void onBeforeRequest(Request request) {

                            }

                            @Override
                            public void onFailure(Call call, IOException e) {


                            }

                            @Override
                            public void onSuccess(Response response, String t) {
                                try {
                                    JSONObject jsonObject=new JSONObject(t);
                                    String code1 = jsonObject.optString("code");
                                    String msg=jsonObject.optString("msg");
                                    if(code1.equals("100")){
                                        ToastTool.toast("解绑成功");
                                        ShareTool.saveInfo(SetActivity.this,"scode","0000000000");
                                        ShareTool.saveInfo(SetActivity.this,"bar_code","");
                                        ShareTool.saveInfo(SetActivity.this,"bar_pwd","");
                                        updateBar("","",""); //解绑更新到数据库
                                        txt.setText("0000000000");
                                        txt.setFocusable(true);
                                        txt.setFocusableInTouchMode(true);
                                    }else {
                                        ToastTool.toast(msg);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onError(Response response, String errorMsg) {

                            }
                        });

                    }else {
                        ToastTool.toast(msg);
                        restShebei(txt);
                    }




                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Response response, String errorMsg) {

            }
        });
    }

    /**
     * @param content
     *
     * 绑定设备号
     */
    private void bindCode(String content, final String device) {
        String path= URLConstant.HOST + URLConstant.FIRMPASSWORD+"firmpwd="+content;
        okTool.doGet(path, new StringCallback() {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onSuccess(Response response, String t) {
                try {
                    JSONObject jsonObject=new JSONObject(t);
                    String code1 = jsonObject.optString("code");
                    String msg=jsonObject.optString("msg");
                    if(code1.equals("100")){   //验证密码成功开始绑定
                        String path= URLConstant.HOST + URLConstant.DEVICEVERIFY+"device_code="+device;
                        okTool.doGet(path, new StringCallback() {
                            @Override
                            public void onBeforeRequest(Request request) {
                            }
                            @Override
                            public void onFailure(Call call, IOException e) {
                            }

                            @Override
                            public void onSuccess(Response response, String t) {
                                try {
                                    JSONObject jsonObject=new JSONObject(t);
                                    String code1 = jsonObject.optString("code");
                                    String msg=jsonObject.optString("msg");
                                    if(code1.equals("100")){
                                        ToastTool.toast("绑定成功");
                                        ShareTool.saveInfo(SetActivity.this,"scode",device);
                                        JSONObject result=jsonObject.optJSONObject("result");
                                        String bar_code=result.optString("bar_code");
                                        String pwd=result.optString("pwd");
                                        ShareTool.saveInfo(SetActivity.this,"bar_code",bar_code);
                                        ShareTool.saveInfo(SetActivity.this,"bar_pwd",pwd);
                                        updateBar(bar_code,device,pwd); //更新到数据库
                                        AlertDialog.Builder builder =new AlertDialog.Builder(SetActivity.this);
                                        builder.setTitle("管理员密码");
                                        builder.setMessage("您的管理员密码为:\n"+pwd+"\n请牢记您的管理员密码用于绑定管理员");
                                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                dialog.dismiss();
                                            }
                                        });
                                        builder.show();
                                    }else {
                                        ToastTool.toast(msg);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }


                            }

                            @Override
                            public void onError(Response response, String errorMsg) {

                            }
                        });



                    }else {
                        ToastTool.toast(msg);
                        bindShebei(device);
                    }




                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Response response, String errorMsg) {

            }
        });
    }

    /**
     * @param content
     *
     * 绑定设备号
     */
    private void requestcmd(String content) {
        String path= URLConstant.HOST + URLConstant.FIRMPASSWORD+"firmpwd="+content;
        okTool.doGet(path, new StringCallback() {
            @Override
            public void onBeforeRequest(Request request) {

            }

            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onSuccess(Response response, String t) {
                try {
                    JSONObject jsonObject=new JSONObject(t);
                    String code1 = jsonObject.optString("code");
                    String msg=jsonObject.optString("msg");
                    if(code1.equals("100")){   //验证密码成功开始绑定
                            setCmd();
                    }else {
                        ToastTool.toast(msg);
                        bindCmd();
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onError(Response response, String errorMsg) {

            }
        });
    }
    /**
     * @param code
     * @param device
     * @param pwd
     * 更新数据到数据库
     */
    private  void updateBar(String code,String device,String pwd) {
        SaveInfo up_info=new SaveInfo();
        up_info.setId(1);
        up_info.setBarcode(code==null?"1":code);
        up_info.setPwd(pwd==null?"1":pwd);
        up_info.setDevice(device==null?"1":device);
        try {
            saveDao.update(up_info);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    /**
     * @param s
     * 往平板写数据
     *
     */
    public void writeToUSb(String s){
        byte[] data = s.getBytes();
        UsbTool.getInstance().writeToUsb(data);
    }
}
